package algorithms.que13;

public class Steque <Item>{
    private class StequeNode {
        Item item;
        StequeNode next;
    }
    private StequeNode first;
    private StequeNode last;
    private int N;
    private boolean isEmpty(){
        return first == null;
    }
    private int size() {
        return N;
    }

    //创建新的节点
    private StequeNode newNode(Item item) {
        StequeNode temp = new StequeNode();
        temp.item = item;
        return  temp;
    }

    //从顶部栈顶/队头插入节点
    public void push(Item item) {
        StequeNode xNode = newNode(item);
        if(isEmpty()) {
            first = xNode;
            last = xNode;
        }else {
            xNode.next = first;
            first = xNode;
        }
        N++;
    }

    //从顶部弹出节点
    public Item pop() {
        if(isEmpty()){
            System.out.println("栈已空");
            return null;
        }
        StequeNode temp = first;
        if(size() == 1) {
            first = null;
            last = null;
        }else {
            first = first.next;
            temp.next = null;
        }
        N--;
        return temp.item;
    }

    //队尾插入节点
    public void enqueue(Item item) {
        StequeNode xNode = newNode(item);
        if(isEmpty()) {
            first = xNode;
            last = xNode;
        }else {
            last.next = xNode;
            last = xNode;
        }
        N++;
    }

    public void printStack() {
        StequeNode temp = first;
        while(temp != null) {
            System.out.println(temp.item);
            temp = temp.next;
        }
    }
}
